<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/27/15
 * Time: 9:28 PM
 */

namespace Plugins\CGWSign;

use Core\PluginContainer;

class Plugin_CGWSign{

    private $db;

    public function __construct()
    {
        $this->db = PluginContainer::getInstance()->singletonMake('database');
    }

    public function fetchTopic(){
        $curl = PluginContainer::getInstance()->make('curl');
        $userList = $this->db->get("select * from plg_cgw_users");
        foreach($userList as $user) {
            $curl->cookies=['kFBk_2132_auth'=>$user->disuz_auth,'kFBk_2132_saltkey'=>$user->disuz_salt];
            $curl->httpHeader=["User-Agent"=>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"];
            $response = $curl->sendRequest("http://www.cgmxw.com/forum.php?mod=guide&view=newthread");
            $response = $this->charsetConv($response);
            if (strpos($response,$user->username) === false) {
                return;
            }
            $response = $this->charsetConv($response);
            if(preg_match_all('/<tbody id="normalthread_.*?">([\s\S]*?)<\/tbody>/',$response,$topicList)===false)
                return;
            foreach($topicList[1] as $topic){
                preg_match('/<td class="by"><a.*?>([\s\S].*?)<\/a>/',$topic,$arr);
                $tag = $arr[1];
                if ((strpos($tag, "资源") !== false || strpos($tag, "角色") !== false || strpos($tag, "模型") !== false) && $tag != "模型王会员打卡区") {
                    preg_match('/<th class="common">[\s\S]*?<a[\s\S]*?>([\s\S].*?)<\/a>/',$topic,$arr);
                    $name = $arr[1];
                    preg_match('/<th class="common">[\s\S]*?<a href="([\s\S].*?)"/',$topic,$arr);
                    $url = $arr[1];
                    $response = $curl->sendRequest($url);
                    if(preg_match('/id="inviteurl" value="([\s\S]*?)"/',$response,$arr)===false)
                        return;
                    $inviteUrl = $arr[1];
                    $this->db->insert("plg_cgw_urls",["title"=>$name,"url"=>$inviteUrl,"timestamp"=>time(),"userid"=>$user->userid]);
                }
            }
        }
    }

    public function doSign(){
        $topicList = $this->db->get("select * from plg_cgw_urls where timestamp>".(time()-28800));
        for($j=0;$j<count($topicList);$j++) {
            $ipList = $this->getIP(10);
            for ($i = 0; $i < 3; $i++) {
                $rnd = rand(0, 9);
                if ($rnd % 2 == 0) {
                    $index = rand(0, 9);
                    $ip = $ipList[$index];
                    array_splice($ipList, $index, 1);
                    $this->excludeIP($ip->id);
                    $http = curl_init();
                    $topicId = rand(0,count($topicList)-1);
                    curl_setopt($http, CURLOPT_URL, $topicList[$topicId]->url);
                    $header = array(
                        'CLIENT-IP:' . $ip->ip,
                        'X-FORWARDED-FOR:' . $ip->ip,
                    );
                    $uar = rand(0, 5);
                    $uaList = [
                        'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)',
                        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)',
                        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
                        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_' . rand(8, 11) . '_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' . rand(40, 45) . '.0.2454.85',
                        'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' . rand(40, 45) . '.0.2454.85',
                        'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'
                    ];
                    $ua = $uaList[$uar];
                    curl_setopt($http, CURLOPT_HTTPHEADER, $header);
                    curl_setopt($http, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($http, CURLOPT_USERAGENT, $ua);
                    curl_exec($http);
                    $redirect = curl_getinfo($http);
                    if ($redirect['http_code'] == 302) {
                        curl_setopt($http, CURLOPT_URL, $redirect['redirect_url']);
                        curl_exec($http);
                    }
                    $wait = rand(1, 60);
                    sleep($wait);
                }
            }
        }
    }

    private function charsetConv($str){
        if(! mb_check_encoding($str, 'utf-8')) {
            $str = mb_convert_encoding($str,'UTF-8','gbk');
        }
        return $str;
    }

    private function getIP($count)
    {
        $array = $this->db->get("select id,ip from plg_cgw_ips where inuse=0");
        if(count($array)<=$count) {
            $this->db->exec("update plg_cgw_ips set inuse=0");
        }
        return $this->db->get("select id,ip from plg_cgw_ips where inuse=0");
    }

    private function excludeIP($id){
        $this->db->update('plg_cgw_ips',["inuse"=>1]," where id=$id");
    }


    public function genIP($start,$end)
    {

        for ($i = 0; $i < 100; $i++) {
            $this->db->exec("insert plg_cgw_ips(ip,inuse) value('" . rand($start, $end) . "." . rand(1, 254) . "." . rand(1, 254) . "." . rand(1, 254) . "',0)");
        }
    }
}